<template>
	<view>
		<up-navbar :title="groupName" @rightClick="uploadShow = true" :autoBack="true" placeholder>
			<template #right>
				<view class="navbar-right">
					<image src="/static/chat/upload2.png" mode="widthFix"></image>
					<up-badge absolute type="error" max="9" :value="uploadList.length" :offset="[-1, -5]"></up-badge>
				</view>
			</template>
		</up-navbar>
		<view class="search">
			<up-search @custom="reset" v-model="keywords" :clearabled="true" actionText="重置"></up-search>
		</view>
		<view class="filter">
			<up-dropdown>
				<up-dropdown-item @change="updateChange" v-model="update" title="更新时间" :options="options[0]"></up-dropdown-item>
				<up-dropdown-item @change="nameChange" v-model="name" title="名称" :options="options[1]"></up-dropdown-item>
				<up-dropdown-item @change="sizeChange" v-model="size" title="大小" :options="options[2]"></up-dropdown-item>
			</up-dropdown>
		</view>
		<view class="container">
			<view v-if="filterData.length == 0">
				<tui-no-data imgWidth="400" imgHeight="350" imgUrl="/static/chat/zwwj.png">暂无文件</tui-no-data>
			</view>
			<up-list :style="listHeightStyle">
				<view v-for="item in filterData" :key="item.fid" class="list-item">
					<view class="icon" @click="cellClick(item)">
						<i v-if="item.type == 1" class="ri-folder-fill icon-dir"></i>
						<image class="thumbnails" v-else-if="item.type == 2" :src="item.url" mode="aspectFit"></image>
						<image class="icon-img" v-else :src="`/static/fileType_big/${setFileIcon(item.file_type)}_b.png`" mode="widthFix"></image>
					</view>
					<view class="content" @click="cellClick(item)">
						<view class="file-name">
							{{item.filename}}
						</view>
						<view class="describe">
							<span v-show="item.type == 0">{{item.formatSize}}</span>
							<i v-show="item.type == 0">·</i>
							<span>{{item.username}}</span>
							<i>·</i>
							<span>{{format(item.update_time)}}</span>
						</view>
					</view>
					<view class="more" @click="handleMore(item)">
						<up-icon name="more-dot-fill" color="#555" size="14"></up-icon>
					</view>
				</view>
			</up-list>
		</view>
		
		<up-popup @close="popupClose" :customStyle="{width: '100vw', height: '52vh', backgroundColor: '#F2F1F6'}" :show="uploadShow" mode="bottom">
			<view class="popup-title">
				上传列表
				<span class="popup-close" @click="popupClose">
					<up-icon name="close" color="#333" :size="20"></up-icon>
				</span>
			</view>
			<!-- <view v-if="filterData.length == 0">
				<tui-no-data imgWidth="400" imgHeight="350" imgUrl="/static/chat/zwwj.png">暂无文件</tui-no-data>
			</view> -->
			<up-list :style="{ height: `42vh`, overflowY: 'auto' }">
				<view v-for="item in uploadList" class="upload-list-item">
					<view class="icon">
						<image src="/static/fileType_big/pdf_b.png" mode="widthFix"></image>
					</view>
					<view class="content">
						<view class="file-name">
							{{item.name}}
						</view>
						<view class="describe">
							{{formatSize(item.totalBytesSent)}}/{{formatSize(item.size)}}
						</view>
						<view class="progress">
							<up-line-progress :percentage="item.percent" height="6px" :showText="false" activeColor="#56A8E6"></up-line-progress>
						</view>
					</view>
					<!-- <view class="more">
						<up-icon name="close-circle" color="#555" size="20"></up-icon>
					</view> -->
				</view>
			</up-list>
		</up-popup>

		<up-modal :show="newFolderShow" @confirm="handleNewFolder" @cancel="newFolderCancel" showCancelButton title="新建文件夹" >
			<view class="slot-content">
				<up-input v-model="folderName" placeholder="请输入文件夹名称" border="surround" clearable></up-input>
			</view>
		</up-modal>
		
		<xe-upload ref="XeUpload" :options="uploadOptions" @beforUpload="beforUpload" @callback="handleUploadCallback"></xe-upload>
		
		<tui-fab @click="fabClick" :btnList="btnList" :maskClosable="true"></tui-fab>
		
		<tui-actionsheet  
		 :show="showActionSheet" 
		 :item-list="itemList" 
		 @click="itemClick" 
		 @cancel="closeActionSheet">
		</tui-actionsheet>

		<tui-modal :button="button" :show="modalShow" @click="modalClick" @cancel="modalShow = false"
		  :content="content"></tui-modal>
			
		<tui-modal :button="button" :show="delShow" @click="delConfirm" @cancel="delShow = false"
			content="确认删除"></tui-modal>
  </view>
</template>

<script>
import { formatFileSize, fileTypeFormat, processImageUrl } from "@/utils/chat.js"
import { chatApi } from '@/apis/cloud/chat'
import { useUserStore, useChatStore } from '@/pinia-store/user'
import { mapStores } from 'pinia'
import dayjs from 'dayjs'

export default {
  name: "GroupFolder",
  data () {
    return {
			content: '是否同步到群消息？',
			listHeightStyle: {}, // 动态计算的样式
			uploadShow: false,
			newFolderShow: false,
			modalShow: false,
			showActionSheet: false,
			delShow: false,
			userInfo: {},
			groupId: null,
			current: null,
			groupName: '',
			fileList: [],
			nextCloud: {},
			folderName: '',
			keywords: '',
			update: 0,
			size: 0,
			name: 0,
			pid: '',
			isPush: 0,
			uploadOptions: {
				url: ''
			},
			itemList: [],
			button: [{
					text: "取消",
					type: "gray",
					plain: true
				},
				{
					text: "确定",
					type: "primary",
					plain: false
			}],
			uploadList: [],
			options: [
				[
					{
						label: '从远到近',
						value: 1,
					},
					{
						label: '从近到远',
						value: 2,
					},
				],
				[
					{
						label: '从A到Z',
						value: 1,
					},
					{
						label: '从Z到A',
						value: 2,
					},
				],
				[
					{
						label: '从大到小',
						value: 1,
					},
					{
						label: '从小到大',
						value: 2,
					},
				]
			],
			btnList: [
				{
					bgColor: "#16C2C2",
					text: "上传文件",
					fontSize: 28,
					color: "#fff",
					imgUrl: '/static/chat/upload.png'
				},
				{
					bgColor: "#64B532",
					text: "新建文件夹",
					fontSize: 28,
					color: "#fff",
					imgUrl: '/static/chat/folder-add.png'
				}
			]
		}
	},
	computed: {
		...mapStores(useUserStore, useChatStore),
		filterData() {
			let list = [...this.fileList]
	
			if (this.keywords) {
				const kw = this.keywords.toLowerCase()
				list = list.filter(item => item.filename.toLowerCase().includes(kw))
			}
	
			if (this.name != 0) {
				list.sort((a, b) => {
					return this.name === 1
						? a.filename.localeCompare(b.filename)
						: b.filename.localeCompare(a.filename)
				})
			}
			if (this.update != 0) {
				list.sort((a, b) => {
					const t1 = new Date(a.update_time).getTime()
					const t2 = new Date(b.update_time).getTime()
					return this.update === 1 ? t1 - t2 : t2 - t1
				})
			}
			if (this.size != 0) {
				list.sort((a, b) => {
					return this.size === 1
						? b.file_size - a.file_size
						: a.file_size - b.file_size
				})
			}
	
			list.sort((a, b) => b.isDir - a.isDir)
	
			return list
		}
	},
	created() {
		this.nextCloud = uni.getStorageSync('next_cloud');

		// #ifdef APP-PLUS
		this.listHeightStyle = {
		  height: `calc(100vh - ${380}rpx)`,
		  overflowY: 'auto',
		};
		// #endif
		
		// #ifdef H5
		const windowHeight = window.innerHeight; // 视口高度
		const listHeight = windowHeight - 142;
		this.listHeightStyle = {
		  height: `${listHeight}px`,
		  overflowY: 'auto',
		};
		// #endif
	},
	onLoad (options) {
		this.groupId = options.groupId;
		this.groupName = options.groupName;
		this.userInfo = this.userStore.user;
		this.pid = options.pid ? options.pid : '';
		this.getGroupFolder();
		
		this.uploadOptions.url = `https://chat.mfarmers.com:88/phpApi/public/index.php/users/Index/uploadImg.html?account=${this.chatStore.imInfo?.account}&department=${this.chatStore.imInfo?.department}&to_account=&bizType=groupchat&bizId=${this.groupId}&pid=${this.pid}`
	},
	methods: {
		async delConfirm(e) {
			if(e.index == 0) return;
			this.delShow = false;
			const params = {
				'data[fid]': this.current.fid
			}
			params.url = 'index.php/users/file/is-empty'
			const msg = await chatApi(this.userInfo?.token, params);
			if(msg.data) {
				params.url = 'index.php/users/file/del'
				const delMsg = await chatApi(this.userInfo?.token, params);
				if(delMsg.code == 200) {
					uni.showToast({
						icon: 'none',
						title: '已删除'
					})
					this.getGroupFolder();
				}else {
					uni.showToast({
						icon: 'none',
						title: '删除失败'
					})
				}
			}else {
				uni.showToast({
					icon: 'none',
					title: '文件夹不为空'
				})
			}
		},
		handleMore(record) {
			this.current = record;
			if(record.uploader == this.chatStore.imInfo?.account) {
				this.itemList =  [{
					text: "删除",
					color: "#2B2B2B"
				}, {
					text: "转发",
					color: "#2B2B2B"
				}]
			}else {
				this.itemList =  [{
					text: "转发",
					color: "#2B2B2B"
				}]
			}
			
			this.showActionSheet = true;
		},
		itemClick(e) {
			console.log(e);
			if(e.text == '删除') {
				this.delShow = true;
			}
			this.closeActionSheet();
		},
		closeActionSheet() {
			this.showActionSheet = false;
		},
		format(date) {
			return dayjs(date).format('YYYY/MM/DD HH:mm')
		},
		formatSize(size) {
			return formatFileSize(size)
		},
		setFileIcon(type) {
			return fileTypeFormat(type)
		},
		isImg(type) {
			return ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp'].includes(type)
		},
		updateChange() {
			this.name = 0;
			this.size = 0
		},
		nameChange() {
			this.update = 0;
			this.size = 0
		},
		sizeChange() {
			this.update = 0;
			this.name = 0
		},
		async handleNewFolder() {
			const params = {
				'data[account]': this.chatStore.imInfo?.account,
				'data[bizId]': this.groupId,
				'data[pid]': this.pid,
				'data[name]': this.folderName,
				'data[bizType]': 'groupchat',
				url: 'index.php/users/file/mkcol'
			}
			const msg = await chatApi(this.userInfo?.token, params);
			if(msg.code == 200) {
				this.getGroupFolder();
			}else {
				uni.showToast({
					icon:"none",
					title: '新建文件夹失败'
				})
			}
			this.newFolderCancel();
		},
		newFolderCancel() {
			this.folderName = '';
			this.newFolderShow = false;
		},
		fabClick(e) {
			if(e.index == 1) {
				this.newFolderShow = true;
			}else {
				this.modalShow = true;
			}
		},
		popupClose() {
			this.uploadShow = false;
		},
		modalClick (e) {
		  if (e.index == 1) {
		    this.chooseFile(1);
				this.isPush = 1;
		  }else {
				this.chooseFile(0);
				this.isPush = 0;
			}
			this.modalShow = false;
		},
		// 选择文件
		async chooseFile(isPush) {
			const _self = this;
			// #ifdef H5
			uni.chooseFile({
				count: 1,
				success(res) {
					if(res.tempFiles[0].size > (1024*1024*50)) {
						uni.showToast({
							icon: 'none',
							duration: 2500,
							title: '请选择小于50MB的文件'
						})
						return
					}
					// 添加队列
					const fileInfo = {
						size: res.tempFiles[0].size,
						name: res.tempFiles[0].name,
						tempFilePaths: res.tempFilePaths[0],
						uuid:  Math.random().toString(36).substring(2, 14),
						percent: 0,
						isPush,
						totalBytesSent: 0,
					}
					_self.uploadList.push(fileInfo);
					
					_self.uploadFile(fileInfo);
				},
				fail(err) {
					console.log(err)
				}
			})
			// #endif
		
			// #ifdef APP-PLUS
			this.$refs.XeUpload.upload('file');
			// #endif
		},
		uploadFile(fileInfo) {
			const _self = this;
			const uploadTask = uni.uploadFile({
				url: _self.uploadOptions.url,
				filePath: fileInfo.tempFilePaths,
				name: 'tmp_name',
				success: (uploadFileRes) => {
					const res = JSON.parse(uploadFileRes.data);
					this.uploadComplete(res.id, fileInfo.isPush);
					
					const findIndex = this.uploadList.findIndex(item => item.uuid == fileInfo.uuid);
					this.uploadList.splice(findIndex, 1);
				}
			});
			// 更新进度 移除队列
			uploadTask.onProgressUpdate((res) => {
				const find = this.uploadList.find(item => item.uuid == fileInfo.uuid);
				find.percent = res.progress;
				find.totalBytesSent = res.totalBytesSent;
			});
		},
		// APP 上传之前添加队列
		beforUpload(e) {
			// 添加队列
			const fileInfo = {
				size: e.fileSize,
				name: e.fileName,
				uuid: e.uuid,
				percent: 0,
				isPush: this.isPush,
				totalBytesSent: 0,
			}
			
			this.uploadList.push(fileInfo);
		},
		// APP 上传 更新进度 移除队列
		handleUploadCallback(e) {
			if (e.type == 'success') {
				const findIndex = this.uploadList.findIndex(item => item.uuid == e.data?.uuid);
				this.uploadList.splice(findIndex, 1);
				this.uploadComplete(e.data[0].response.id, this.isPush);
			}else {
				const find = this.uploadList.find(item => item.uuid == e.data?.uuid);
				if(find) {
					find.percent = e.data.progress;
					find.totalBytesSent = e.data.totalBytesSent;
				}
			}
		},
		// H5 APP 上传完成 更新列表
		async uploadComplete(fid, isPush) {
			const params = {
				url: 'index.php/users/file/'+fid,
				method: 'get'
			}
			const msg = await chatApi(this.userInfo?.token, params);
			if(isPush == 1) {
				const params = {
					url: `index.php/users/message/${fid}/notify-file-uploaded`,
				}
				const pushMsg = await chatApi(this.userInfo?.token, params);
			}
			
			this.getGroupFolder();
		},
		cellClick(item) {
			// 打开文件夹
			if(item.type == 1) {
				uni.navigateTo({
				  url: `/pages/chat/message/common/chatGroupFolder?groupId=${this.groupId}&groupName=${this.groupName}&pid=${item.fid}`
				})
				return
			}
			
			// 图片预览
			if(item.type == 2) {
				const cache = item.url.replace(/\/thumb_([^\/.]+\.(?:png|jpe?g|gif))/i, '/$1')
				uni.previewImage({
					urls: [cache],
				})
				return
			}
			
			// 文件预览
			const type = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'];
			const that = this;
			let url = ''
			const xtoken = this.nextCloud.xtoken
			
			const fileName = encodeURIComponent(encodeURIComponent(item.filename)); // 双重编码
			const fileurl = encodeURIComponent(item.url); // 单次编码
			
			if (type.includes(item.file_type)) {
			  let previewUrl = '';
			  if (xtoken) {
			    previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?xtoken=${xtoken}&nc_id=${item.nc_id ? item.nc_id : ''}&fileName=${fileName}&type=mobile&user=${that.userStore.user.worker_id}&url=${fileurl}`;
			  } else {
			    previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?fileName=${fileName}&type=mobile&user=${that.userStore.user.worker_id}&url=${fileurl}`;
			  }
			
			  const encodedData = encodeURIComponent(JSON.stringify({ previewUrl }));
			  url = `/pages/chat/message/common/previewDoc?data=${encodedData}`;
			} else {
			  url = `/pages/chat/message/common/downloadDoc?fileName=${fileName}&fileSize=${item.formatSize}&url=${fileurl}&fid=${item.fid}&type=${item.file_type}`;
			}
			
			uni.navigateTo({ url });
			
		},
		async getGroupFolder() {
			const params = {
				'data[token]': this.userInfo?.token,
				'data[bizId]': this.groupId,
				'data[pid]': this.pid,
				'data[chatType]': 'group',
				url: 'index.php/users/file/page'
			}
			const msg = await chatApi(this.userInfo?.token, params);
			msg.data.forEach(item => {
				item.formatSize = formatFileSize(item.file_size);
				item.isDir = item.file_type == 'dir' ? 1 : 0;
				if(item.file_type == 'dir') {
					item.type = 1
				}else if(this.isImg(item.file_type)) {
					item.type = 2
				}else {
					item.type = 3
				}
				item.url = processImageUrl(item.url);
			})

			this.fileList = msg.data;
		},
		setIcon(item) {
			return item2.resourcetype != '' ? `/static/fileType_big/folder_b.png` : `/static/fileType_big/${setFileIcon(item.name)}_b.png`
		},
		reset() {
			this.update = 0;
			this.name = 0;
			this.size = 0;
			this.keywords = '';
		},
	}
}
</script>
<style>
	.u-dropdown__menu {
		z-index: 0 !important;
	}
</style>
<style scoped lang="scss">
page {
  width: 100vw;
}
.search {
	padding: 0 10px 10px 10px;
}
.container {
	padding: 0 14px 10px 14px;
}
.list-item {
	display: flex;
	align-items: center;
	margin-bottom: 24rpx;
	.icon {
		width: 72rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.icon-dir {
		font-size: 72rpx;
		color: #68b4e1;
		line-height: 32rpx;
	}
	.thumbnails {
		width: 72rpx;
		height: 72rpx;
	}
	.icon-img {
		width: 56rpx;
	}
	.content {
		margin-left: 8px;
		flex: 1;
		.file-name {
			width: 72vw;
			font-size: 28rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			color: #222;
		}
		.describe {
			font-size: 22rpx;
			color: #666;
		}
	}
}
.navbar-right {
	position: relative;
}
.navbar-right  image {
	width: 50rpx;
}
.popup-title {
	position: relative;
	text-align: center;
	line-height: 40px;
}
.popup-close {
	position: absolute;
	right: 10px;
	top: 50%;
	transform: translateY(-45%);
}
.upload-list-item {
	display: flex;
	align-items: center;
	margin: 0 14px 10px 16px;
}
.icon image {
	width: 58rpx;
}
.content {
	width: calc(100% - 58rpx - 50rpx - 10rpx - 10rpx - 4rpx);
	margin: 0 10px;
	.file-name {
		font-size: 28rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.describe {
		font-size: 24rpx;
		color: #555;
		margin-bottom: 6px;
	}
}
.more {
	margin-left: 8rpx;
}
</style>
